/**
 * @Author: 宋计民
 * @Date: 2022/11/3
 * @Version: 1.0
 * @Content: 下载文件  1
 */
import { getTokenUtil } from '@utils'

/**
 * 下载单个文件
 * @param url 文件地址
 * @param {string|boolean} fileName 文件名称 非必填如果没有则会在下载的时候自动取后端设置的文件名
 */
export function downloadFileUtil(url: string, fileName = '') {
  const _a = document.createElement('a')
  if (url.includes('?')) {
    url += `&token=${getTokenUtil()}`
  } else {
    url += `?token=${getTokenUtil()}`
  }
  _a.setAttribute('href', url)
  _a.setAttribute('download', fileName)
  _a.click()
  _a.remove()
}

/**
 * 通过Ajax下载文件
 * @param response
 * @param fileName
 */
export function downloadFileForAjax(response: any, fileName = '') {
  const blob = new Blob([response.data], { type: 'application/pdf' })
  const contentDisposition = response.headers['content-disposition']
  if (contentDisposition) {
    fileName = window.decodeURI(contentDisposition.split('=')[1])
  }
  if ('download' in document.createElement('a')) {
    const link = document.createElement('a')
    link.href = window.URL.createObjectURL(blob)
    link.download = fileName
    link.click()
    window.URL.revokeObjectURL(link.href) // 释放
    link.remove()
  }
}

/**
 * 从文件服务器下载
 * @param fileId
 */
export function downloadFileFromFileServer(fileId: string) {
  console.log(fileId)
  downloadFileUtil(
    `/platform-api/downloadFile?fileId=${fileId}&request-type=cloud`
  )
}

/**
 * 加载文件
 * @param {*} data
 * @returns
 */
export function downLoadFile(fileId: string) {
  if (!fileId) {
    return false
  }
  return `/platform-api/downloadFile?fileId=${fileId}&request-type=cloud`
}
